package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.rdb.api.AdSetRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.AdSet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Sisi on 15-2-26.
 */
@Service
public class AdSetRdbServiceImpl extends DaoTemplate implements AdSetRdbService {
    protected Map<String, String> fieldColumn = new HashMap<>();

    public AdSetRdbServiceImpl() {
        fieldColumn.put("id", "id");
        fieldColumn.put("adSetId", "ad_set_id");
        fieldColumn.put("fbAccountId", "fb_account_id");
        fieldColumn.put("campaignGroupId", "campaign_group_id");
        fieldColumn.put("publishBatchId", "publish_batch_id");
        fieldColumn.put("fbConnectionObjectId", "fb_connection_object_id");
        fieldColumn.put("productConfId", "product_conf_id");
        fieldColumn.put("name", "name");
        fieldColumn.put("campaignStatus", "campaign_status");
        fieldColumn.put("dailyBudget", "daily_budget");
        fieldColumn.put("lifetimeBudget", "lifetime_budget");
        fieldColumn.put("updatedTime", "updated_time");
        fieldColumn.put("updatedUtcTime", "updated_utc_time");
        fieldColumn.put("createdTime", "created_time");
        fieldColumn.put("createdUtcTime", "created_utc_time");
        fieldColumn.put("startTime", "start_time");
        fieldColumn.put("endTime", "end_time");
        fieldColumn.put("startUtcTime", "start_utc_time");
        fieldColumn.put("endUtcTime", "end_utc_time");
        fieldColumn.put("bidInfo", "bid_info");
        fieldColumn.put("bidType", "bid_type");
        fieldColumn.put("targeting", "targeting");
        fieldColumn.put("promotedObject", "promoted_object");
        fieldColumn.put("localUpdatedTime", "local_updated_time");
        
        //v2.4 新增
        fieldColumn.put("adlabels", "adlabels");
        fieldColumn.put("frequency_cap", "frequency_cap");
        fieldColumn.put("frequency_cap_reset_period", "frequency_cap_reset_period");
        fieldColumn.put("lifetime_frequency_cap", "lifetime_frequency_cap");
        fieldColumn.put("lifetime_imps", "lifetime_imps");
        fieldColumn.put("optimization_goal", "optimization_goal");
        //fieldColumn.put("product_ad_behavior", "product_ad_behavior");
        fieldColumn.put("rf_prediction_id", "rf_prediction_id");
        fieldColumn.put("rtb_flag", "rtb_flag");
        fieldColumn.put("pacing_type", "pacing_type");
        fieldColumn.put("budget_remaining", "budget_remaining");
        fieldColumn.put("bid_amount", "bid_amount");
        fieldColumn.put("billing_event", "billing_event");
        fieldColumn.put("buying_type", "buying_type");
        fieldColumn.put("effectiveStatus", "effective_status");
        //支持自动出价
        fieldColumn.put("isAutobid", "is_autobid");
    }



    @Override
    public AdSet findByAdSetId(Long adSetId) {
        String sql = "SELECT * FROM ad_set WHERE ad_set_id = ?";
        return findOne(sql, new Object[]{adSetId}, DefaultRowMapper.autoRowMapper(AdSet.class));
    }



	/**
	 * @discription
	 * @author yanghao       
	 * 创建时间 2015年3月19日 下午12:04:24      
	 * @param fields     
	 * @see com.ndp.fb.rdb.api.AdSetRdbService#updateAdSetsByAdSetIds(java.util.List)     
	 */  
	    
	@Override
	public void updateAdSetsByAdSetIds(List<Map<String, Object>> fields) {
		 //构造sql
        StringBuilder sb;
        for (int i = 0; i < fields.size(); i++) {
            sb = new StringBuilder();
            List<Object[]> sqlParams = new ArrayList<>();
            sb.append("update ad_set set ");
            Map<String, Object> fieldMap = fields.get(i);
            if(!fieldMap.containsKey("localUpdatedTime")){
            	fieldMap.put("localUpdatedTime", System.currentTimeMillis());
    		}
            List<Object> value = new ArrayList<>();
            int k = 0;
            Object adSetIdValue = fieldMap.remove("adSetId");
            //id是不能更新的
            fieldMap.remove("id");
            for (Map.Entry<String, Object> stringObjectEntry : fieldMap.entrySet()) {
                String key = stringObjectEntry.getKey();
                value.add(stringObjectEntry.getValue());
                if (++k == fieldMap.size()) {
                    sb.append(" " + fieldColumn.get(key) + " = ? ");
                } else {
                    sb.append(" " + fieldColumn.get(key) + " = ? ,");
                }
            }
            value.add(adSetIdValue);
            sqlParams.add(value.toArray());
            sb.append(" where ad_set_id = ?");
            getJdbcTemplate().batchUpdate(sb.toString(), sqlParams);
        }
	}

    @Override
    public void save(final AdSet adSet) {
        //local_updated_time 不处理，默认零。
        saveResultId(adSet);
    }

    @Override
    public void updateEcTemplateMaterielId(Long adSetId, Long ecTemplateMaterielId) {
        String sql = "UPDATE ad_set SET ec_template_materiel_id = ? WHERE ad_set_id=?";
        getJdbcTemplate().update(sql, new Object[]{ecTemplateMaterielId, adSetId});
    }

    @Override
    public void updateProductSetMongoId(String productSetMongoId,Long adSetId) {
        String sql = "UPDATE ad_set SET product_set_mongo_id = ? WHERE ad_set_id=?";
        getJdbcTemplate().update(sql, new Object[]{productSetMongoId, adSetId});
    }
}
